package cn.chendd.example.jpa.nativequery;

import cn.chendd.example.jpa.components.SpringBeanFactory;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.env.Environment;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author chendd
 * @date 2020/5/13 21:11
 */
public class InnerVariable {

    /**
     * 完整表达式
     */
    private static final String VARIABLE_REGEX = "\\$\\{(.*?)\\}";
    /**
     * 匹配从application.yml文件中读取的变量
     */
    private static final String VALUE_REGEX = "value\\((.*?)\\)";
    /**
     * 变量前置插入
     */
    private static final String BEFORE_REGEX = "before\\((.*?)\\)";
    /**
     * 变量后置追加
     */
    public static final String AFTER_REGEX = "after\\((.*?)\\)";

    public static String reloadVariable(String text) {
        Environment env = SpringBeanFactory.getBean(Environment.class);
        Matcher matcher = Pattern.compile(VARIABLE_REGEX , Pattern.CASE_INSENSITIVE).matcher(text);
        if(matcher.find()){
            StringBuilder builder = new StringBuilder();
            String group = matcher.group(1);
            Matcher beforeMatcher = Pattern.compile(BEFORE_REGEX , Pattern.CASE_INSENSITIVE).matcher(group);
            if(beforeMatcher.find()){
                builder.append(beforeMatcher.group(1));
            }
            Matcher valueMatcher = Pattern.compile(VALUE_REGEX , Pattern.CASE_INSENSITIVE).matcher(group);
            if(valueMatcher.find()){
                String value = valueMatcher.group(1);
                builder.append(env.getProperty(value));
            }
            Matcher afterMatcher = Pattern.compile(AFTER_REGEX , Pattern.CASE_INSENSITIVE).matcher(group);
            if(afterMatcher.find()){
                builder.append(afterMatcher.group(1));
            }
            String all = matcher.group();
            text = text.replace(all , builder.toString());
        }
        return text;
    }

}
